/*
 Copyright (c) Whitemice Consulting, 2007, 2008, 2009
 Adam Tauno Williams <awilliam@whitemice.org>
 License: MIT/X11

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using CookComputing.XmlRpc;

namespace Whitemice.ZOGI
{
  public class Project : OwnedEntity, 
                         IZOGIStorable,
                         ITaskContainer,
                         IContactContainer,
                         INoteContainer,
                         IEnterpriseContainer
  {
    public Project() : base()
    {
    }
          
    public Project(IDictionary<string,object> x, int d)
      : base(x, d)
    {
    }
    
    internal override void Take(IDictionary<string,object> x, int d)
    {
      base.Take(x, d);
      Name = AsString(x, "name");
      Number = AsString(x, "number");
      Kind = AsString(x, "kind");
      Comment = AsString(x, "comment");
      SetStatus(AsString(x, "status"));
      SetFolderId(AsInt32(x, "folderObjectId"));
      SetPlaceHolder(AsBoolean(x, "placeHolder"));
      Start = AsDateTime(x, "startDate");
      End = AsDateTime(x, "endDate");
    }
    
    //TODO: Correctly implement permissions
   	public override bool CanRead { get { return true; } }
		public override bool CanDelete { get { return CanModify; } }
		//public override bool CanModify { get { return HasHint("WRITE"); } }
    public override bool CanModify { get { return true; } }
       
    public override bool FirstClass { get { return true; } }
       
    public string Name { get; set; }
    public string Number { get; set; }
    public string Kind { get; set; }
    public string Comment { get; set; }
      
    protected string _status;
    protected void SetStatus(string s) { _status = s; }
    public string Status { get { return _status; } } 
      
    protected int _folderId;
    protected void SetFolderId(int f) { _folderId = f; }
    public int FolderId { get { return _folderId; } }
    
    public Folder Folder 
    { 
      get { return Server.Cache.Get<Folder>(FolderId); } 
    }

    public IEnumerable<int> TaskIds
    {
      get
      {
        IList<int> taskIds;

        taskIds = new List<int>();
        foreach(Task t in Tasks)
          taskIds.Add(t.ObjectId);
        return taskIds;
      }
    } // end TaskIds
    
    public IEnumerable<Task> Tasks
    {
      get { return Server.Cache.GetChildrenOf<Task>(ObjectId); }
    }

    public void GetTasks(MultiResultCallback callback, object context)
    {
      FetchCommand  command;

      command = new FetchCommand(TaskIds, 65535, context);
      command.Callback = callback;
      Server.Connection.RunCommand(command);
    } // end GetTasks
    
    public IEnumerable<Note> Notes
    {
      get { return Server.Cache.GetNotesFor(this); }
    }

    public IEnumerable<int> NoteIds
    {
      get
      {
        IList<int> noteIds;
        noteIds = new List<int>();
        foreach(Note note in Notes)
          noteIds.Add(note.ObjectId);
        return noteIds;
      }
    }

    public void GetNotes(MultiResultCallback callback, object context)
    {
      callback(this,
               new RPCEventArgs("GetNotes", 
                                (Notes as IEnumerable<Entity>), 
                                context, 
                                null));
    }
    
    public IEnumerable<int> ContactIds
    {
      get { return this.SubordinatesForKey("_CONTACTS"); }
    }

    public void GetContacts(MultiResultCallback callback, object context)
    {
      FetchCommand      command;
      IEnumerable<int>  contactIds;

      contactIds = ContactIds;
      if (contactIds.Count() > 0)
      {
        command = new FetchCommand(ContactIds, 65535, context);
        command.Callback = callback;
        Server.Connection.RunCommand(command);
      } else
        {
          RPCEventArgs args = new RPCEventArgs("", new List<Whitemice.ZOGI.Entity>(), context, null);
          callback(this, args);
        }
    } // end GetContacts
    
    public IEnumerable<int> EnterpriseIds
    {
      get { return this.SubordinatesForKey("_ENTERPRISES"); }
    }

    public void GetEnterprises(MultiResultCallback callback, object context)
    {
      FetchCommand  command;
      if (EnterpriseIds.Count() > 0)
      {
        this.ZLOG(string.Format("{0}#{1} requeting {2} enterprises.", 
                                this, 
                                ObjectId, 
                                EnterpriseIds.Count()));
        command = new FetchCommand(EnterpriseIds, 65535, context);
        command.Callback = callback;
        Server.Connection.RunCommand(command);
      } else callback(this, new RPCEventArgs("", new List<Whitemice.ZOGI.Entity>(), context, null)); 
    }
      
    protected bool _fake;
    protected void SetPlaceHolder(bool f) { _fake = f; }
    public bool IsPlaceHolder { get { return _fake; } }
      
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
    
    public override void Assign(Entity _entity)
    {
      if (_entity is Whitemice.ZOGI.Contact)
      {
        // contact assignment
        AddSubordinate("_CONTACTS", _entity.ObjectId);
        _entity.AddSubordinate("_PROJECTS", ObjectId);
      } else if (_entity is Whitemice.ZOGI.Enterprise)
				{
			    AddSubordinate("_ENTERPRISES", _entity.ObjectId);
					_entity.AddSubordinate("_PROJECTS", ObjectId);
				}
    } // end Assign
    
    public override void Unassign(Entity _entity)
    {
      if (_entity is Whitemice.ZOGI.Contact)
      {
        // contact assignment 
        RemoveSubordinate("_CONTACTS", _entity.ObjectId);            
        _entity.RemoveSubordinate("_PROJECTS", ObjectId);         
      } else if (_entity is Whitemice.ZOGI.Enterprise)
        {
          // project assignment
          RemoveSubordinate("_ENTERPRISES", _entity.ObjectId);                 
          _entity.RemoveSubordinate("_PROJECTS", ObjectId);             
        } // end if-entity-is-project
    } // end Unassign
    
    public override XmlRpcStruct Encode()
    {
      XmlRpcStruct                               rpcStruct;
      XmlRpcStruct                               tmpStruct;
      XmlRpcStruct[]                             tmpArray;
      IEnumerable<Whitemice.ZOGI.Note>           notes;
      int                                        count, i;
      
      rpcStruct = base.Encode();
      if (ObjectId < 1)
        rpcStruct.Add("objectId", 0);
        else rpcStruct.Add("objectId", ObjectId);
      rpcStruct.Add("entityName", "Project");
      rpcStruct.Add("name", Name);
      rpcStruct.Add("number", Number);
      rpcStruct.Add("startDate", Start);
      rpcStruct.Add("endDate", End);
      //rpcStruct.Add("comment", Comment);
      if (IsPlaceHolder)
        rpcStruct.Add("placeHolder", 1);
      else
        rpcStruct.Add("placeHolder", 0);

      // add notes to project
      notes = this.Notes;
      tmpArray = new XmlRpcStruct[notes.Count()];
      count = 0;
      while (count < tmpArray.Length)
      {
        tmpArray[count] = notes.ElementAt(count).Encode();
        count++;
      } // end for-note
      rpcStruct.Add("_NOTES", tmpArray);
      this.ZLOG("Encoded {0} notes to Project#{1}",
                count,
                ObjectId);
      tmpArray = null;
      
      // add contacts to project
      count = 0;
 			tmpArray = new XmlRpcStruct[ContactIds.Count()];
 			foreach(int contactId in ContactIds)
 			{
 			  tmpStruct = new XmlRpcStruct();
 			  tmpStruct.Add("entityName", "assignment");
 			  tmpStruct.Add("targetEntityName", "Contact");
 			  tmpStruct.Add("targetObjectId", contactId);
 			  tmpStruct.Add("sourceObjectId", ObjectId);
 			  tmpStruct.Add("sourceEntityName", EntityName);
 			  tmpArray[count] = tmpStruct;
 			  count++;
 			} // end for-contactId
 			rpcStruct.Add("_CONTACTS", tmpArray);
      this.ZLOG("Encoded assignment of {0} contacts to Project#{1}",
                count,
                ObjectId);
 			tmpArray = null;
      
      // add enterprises to project
      count = 0;
 			tmpArray = new XmlRpcStruct[EnterpriseIds.Count()];
 			foreach(int enterpriseId in EnterpriseIds)
 			{
 			  tmpStruct = new XmlRpcStruct();
 			  tmpStruct.Add("entityName", "assignment");
 			  tmpStruct.Add("targetEntityName", "Enterprise");
 			  tmpStruct.Add("targetObjectId", enterpriseId);
 			  tmpStruct.Add("sourceObjectId", ObjectId);
 			  tmpStruct.Add("sourceEntityName", EntityName);
 			  tmpArray[count] = tmpStruct;
 			  count++;
 			} // end for-enterpriseId
 			rpcStruct.Add("_ENTERPRISES", tmpArray);
      this.ZLOG("Encoded assignment of {0} enterprises to Project#{1}",
                count,
                ObjectId);
      tmpArray = null;
      
      // return struct
      return rpcStruct;
    } // end Encode    
  }
}